import 'dart:io';

import 'package:demo/pages/ble/ble_cubit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_htmlful/Div.dart';
import 'package:flutter_htmlful/Style.dart';
import 'package:permission_handler/permission_handler.dart';

class BlePage extends StatefulWidget {
  const BlePage({super.key});

  @override
  State<BlePage> createState() => _BlePageState();
}

class _BlePageState extends State<BlePage> with WidgetsBindingObserver {
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => BleCubit(),
      child: BlocBuilder<BleCubit, BleState>(
        builder: (BuildContext context, BleState state) {
          return SafeArea(
            child: Scaffold(
              appBar: AppBar(
                title: const Text('BLE'),
              ),
              body: Div(
                style: Style(
                  backgroundColor: Colors.white,
                  height: double.infinity,
                  width: double.infinity,
                  scrollable: true,
                ),
                body: [
                  ElevatedButton(
                    onPressed: () {
                      startScan();
                    },
                    child: const Text('发送'),
                  ),
                  Padding(padding: MediaQuery.of(context).viewInsets),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  startScan() async {
    if (await FlutterBluePlus.isSupported == false) {
      debugPrint("Bluetooth not supported by this device");
      return;
    }
    // var subscription = FlutterBluePlus.adapterState.listen((BluetoothAdapterState state) {
    //   debugPrint('aaaa : ' + state.toString());
    //   if (state == BluetoothAdapterState.on) {
    //     // usually start scanning, connecting, etc
    //   } else {
    //     if (Platform.isAndroid) {
    //       FlutterBluePlus.turnOn();
    //     }
    //   }
    // });
    var subscription = FlutterBluePlus.onScanResults.listen(
      (results) {
        if (results.isNotEmpty) {
          ScanResult r = results.last; // the most recently found device
          print('${r.device.remoteId}: "${r.advertisementData.advName}" found!');
        }
      },
      onError: (e) => print(e),
    );

    FlutterBluePlus.cancelWhenScanComplete(subscription);
    await FlutterBluePlus.adapterState.where((val) => val == BluetoothAdapterState.on).first;

    await FlutterBluePlus.startScan(
        withServices: [Guid("180D")], // match any of the specified services
        withNames: ["Bluno"], // *or* any of the specified names
        timeout: Duration(seconds: 15));

    await FlutterBluePlus.isScanning.where((val) => val == false).first;
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    FlutterBluePlus.setLogLevel(LogLevel.verbose);
    Permission.bluetoothConnect.request();
    Permission.bluetooth.request();
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    var size = MediaQuery.of(context).size.height;
    debugPrint("didChangeMetrics $size");
  }
}
